<template>
  <div>
    <a-form
        auto-label-width
        ref="loginForm"
        :model="form"
        :rules="rules"
        @submit="handleSubmit"
        size="large"
        style="margin-top: 10px"
    >
      <a-form-item
          label="账&nbsp;&nbsp;&nbsp;&nbsp;号"
          field="userAccount"
          validate-trigger="blur"
      >
        <a-input
            v-model="form.userAccount"
            :max-length="12"
            show-word-limit
            placeholder="请输入账号"
            allow-clear
        />
      </a-form-item>
      <a-form-item
          label="用户名"
          field="userName"
          validate-trigger="blur"
      >
        <a-input
            v-model="form.userName"
            :max-length="12"
            show-word-limit
            placeholder="请输入用户名"
            allow-clear
        />
      </a-form-item>
      <a-form-item
          label="密&nbsp;&nbsp;&nbsp;&nbsp;码"
          field="userPassword"
          validate-trigger="blur"
      >
        <a-input-password
            v-model="form.userPassword"
            placeholder="请输入密码"
            :max-length="30"
            show-word-limit
            allow-clear
        />
      </a-form-item>
      <a-form-item
          label="确&nbsp;&nbsp;&nbsp;&nbsp;认"
          field="checkPassword"
          validate-trigger="blur"
      >
        <a-input-password
            v-model="form.checkPassword"
            placeholder="请确认密码"
            :max-length="30"
            show-word-limit
            allow-clear
        />
      </a-form-item>
      <a-row :gutter="24">
        <a-col :span="14">
          <a-form-item
              field="imageCaptcha"
              label="验证码"
              validate-trigger="blur"
          >
            <a-verification-code
                v-model="form.imageCaptcha"
                :length="4"
            />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-tooltip content="点击图片刷新" placement="top">
            <img
                :src="captcha.captchaImage"
                style="width: 100%;border: 1px solid #ccc"
                alt=""
                @click="getCaptcha()"
            >
          </a-tooltip>
        </a-col>
      </a-row>
      <a-form-item
          label="邮&nbsp;&nbsp;&nbsp;&nbsp;箱"
          field="email"
          validate-trigger="blur"
      >
        <a-input
            v-model="form.email"
            :max-length="30"
            show-word-limit
            placeholder="请输入邮箱"
            allow-clear
        />
      </a-form-item>
      <a-row :gutter="24">
        <a-col :span="16">
          <a-form-item
              field="emailCaptcha"
              label="验证码"
              validate-trigger="blur"
          >
            <a-verification-code
                v-model="form.emailCaptcha"
                :length="6"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-button
              type="primary"
              size="large"
              :loading="buttonLoading"
              long
              @click="getEmailCaptcha"
          >
            {{ buttonLoading ? `${loadingTime}秒后获取` : '获取验证码' }}
          </a-button>
        </a-col>
      </a-row>
      <a-button
          html-type="submit"
          style="margin: 20px 0"
          type="primary"
          long
      >
        立即注册
      </a-button>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import request from "../axios/axios";
import { Message } from '@arco-design/web-vue';
import {onMounted, ref} from "vue";
import router from "../router";

const loginForm = ref()

const captcha = ref({
  captchaImageId: "",
  captchaEmailId: "",
  captchaImage: ""
})

const form = ref({
  userAccount: "",
  userName: "",
  email: "",
  userPassword: "",
  checkPassword: "",
  imageCaptcha: "",
  emailCaptcha: "",
})

onMounted(() => {
  getCaptcha()
})

const getCaptcha = () =>{
  request.get("/api/auth/captcha").then(res => {
    captcha.value.captchaImageId = res.data.data.captchaId
    captcha.value.captchaImage = "data:image/gif;base64," + res.data.data.captchaImage
  })
}

const buttonLoading = ref(false)
const loadingTime = ref(60)

const loading = () => {
  loadingTime.value = 60
  const clean = setInterval(() => {
    loadingTime.value = loadingTime.value - 1;
    if(loadingTime.value <= 0){
      buttonLoading.value = false
      clearInterval(clean);
    }
  }, 1000);
}

const getEmailCaptcha = () =>{
  if (form.value.email == null || form.value.email === ""){
    loginForm.value.setFields({
      email: {
        status: 'error',
        message: '请先填写邮箱'
      },
    })
    return
  }
  // 校验邮箱格式
  if (!form.value.email.includes("@") || !form.value.email.includes(".")){
    loginForm.value.setFields({
      email: {
        status: 'error',
        message: '请输入正确的邮箱格式'
      },
    })
    return
  }
  buttonLoading.value = true
  loading()
  request.get("/api/auth/send/email",{
    params: {
      email: form.value.email
    }
  }).then(res => {
    if (res.data.success === true){
      Message.success("验证码发送成功！有效期5分钟")
      captcha.value.captchaEmailId = res.data.data.emailId
    }
  })
}

const rules = {
  userAccount: [
    {required: true, message: "请输入账号", trigger: "blur"},
    {length: 12, message: "长度为12个字符", trigger: "blur"}
  ],
  userPassword: [
    {required: true, message: "请输入密码", trigger: "blur"},
    {minLength: 6, maxLength: 30, message: "长度至少 6 个字符", trigger: "blur"}
  ],
  imageCaptcha: [
    {required: true, message: "请输入验证码", trigger: "blur"},
    {length: 4, message: "长度为4个字符", trigger: "blur"}
  ],
  email: [
    {required: true, message: "请输入邮箱", trigger: "blur"},
    {minLength: 6, maxLength: 30, message: "长度为 6 - 30 个字符", trigger: "blur"},
  ],
  emailCaptcha: [
    {required: true, message: "请输入邮箱验证码", trigger: "blur"},
    {length: 6, message: "长度为 6 个字符", trigger: "blur"}
  ],
  checkPassword: [
    {required: true, message: "请输入密码", trigger: "blur"},
    {minLength: 6, maxLength: 30, message: "长度至少 6 个字符", trigger: "blur"}
  ],
  userName: [
    {required: true, message: "请输入用户名", trigger: "blur"},
    {minLength: 2, maxLength: 30, message: "长度至少 2 个字符", trigger: "blur"}
  ],
}

const handleSubmit = ({values, errors}) => {
  if (errors){
    Message.error("请将信息填写完整")
    return
  }
  if (form.value.userPassword !== form.value.checkPassword){
    loginForm.value.setFields({
      checkPassword: {
        status: 'error',
        message: '两次输入密码不一致'
      },
    })
    return
  }
  request.post("/api/auth/register",{
    captchaDto: {
      captchaId: captcha.value.captchaImageId,
      captchaValue: form.value.imageCaptcha
    },
    checkPassword: form.value.checkPassword,
    email: form.value.email,
    emailDto: {
      emailCode: form.value.emailCaptcha,
      emailId: captcha.value.captchaEmailId
    },
    userAccount: form.value.userAccount,
    userPassword: form.value.userPassword,
    userName: form.value.userName
  }).then(res => {
    if (res.data.success === true){
      Message.success("注册成功！")
      router.push("/login")
    }
  })

}
</script>

<style scoped>

</style>
